package pub.guoxin.oops.collector.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.constants.CDI;
import pub.guoxin.oops.constants.DDI;
import pub.guoxin.oops.constants.TopicName;
import pub.guoxin.oops.msg.MessageDataProducer;
import pub.guoxin.oops.utils.BytesUtils;

import javax.annotation.Resource;

/**
 * Created by guoxin on 17-10-11.
 */
@Slf4j
@Component
public class DataGatherServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Resource
    private MessageDataProducer messageDataProducer;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info(ctx.channel().remoteAddress() + " 连接到服务器。");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        log.info("UDP数据来源：{}：", packet.sender().getAddress(), packet.sender().getPort());

        ByteBuf buf = packet.copy().content();
        byte[] buffer = new byte[buf.readableBytes()];
        if (buffer.length == 0){
            return;
        }
        buf.readBytes(buffer);
        String messageBody = BytesUtils.toHexString(buffer);
//        String[] strings = new String[messageBody.length() / 2];
//        for (int i = 0; i < messageBody.length() / 2; i++) {
//            strings[i] = messageBody.substring(i * 2, i * 2 + 2);
//        }
        int length = messageBody.length() / 2;
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ starting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

        log.info("========================================================================================");
        log.info("有符号Byte数据：{}", messageBody);
        log.info("有符号Byte数据：{}", length);
        log.info("========================================================================================");

        // 验证数据长度是否符合16进制标准
        if (length % 2 == 0 && length % DDI.TOTAL_LENGTH == CDI.TOTAL_LENGTH){// 验证数据格式是否错误
            messageDataProducer.sender(TopicName.DATA_REPLICATED_TOPIC, messageBody);
        } else {
            log.error("验证数据长度是否符合16进制标准,或者数据的长度不符合length % 设备长度 == 通讯模块长度");
        }
        ctx.channel().writeAndFlush("1");
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ending ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }

//    private String getMessageBody(DatagramPacket packet) {
//        String messageBody = packet.content().toString(CharsetUtil.UTF_8);
//        return messageBody;
//    }

    /*
    0  = 0 1
    1  = 2 3
    2  = 4 5
    3  = 6 7
     */
    public static void main(String[] args) {
        int[] arr = new int[10];
        int i = arr[-1];
        System.out.println(i);
    }
}
